package com.scm.crm.frameworks.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {
    @Resource
    private SessionFactory sessionFactory;

    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("org.h2.Driver");
        druidDataSource.setUrl("jdbc:h2:tcp://localhost/../gaoyihong/ServerDB");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root123456");
        druidDataSource.setMaxWait(60000);
        druidDataSource.setTestWhileIdle(false);
        return druidDataSource;
    }
    @Bean
    public LocalSessionFactoryBean entityManagerFactoryBean(){
        Properties properties = new Properties();
        properties.setProperty("hibernate.format_sql","true");
        properties.setProperty("hibernate.show_sql","true");
        properties.setProperty("hibernate.hbm2ddl.auto","update");
        properties.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setPackagesToScan("com.scm.crm.frameworks.pojo");
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setHibernateProperties(properties);
        return sessionFactoryBean;
    }
    /**
     * 此类是处理hibernate 的模板采用的
     * org.springframework.orm.hibernate5.HibernateTemplate;
     * 通过依赖注入到spring中
     * */
    @Bean
    public HibernateTemplate hibernateTemplate(){
        HibernateTemplate hibernateTemplate = new HibernateTemplate();
        hibernateTemplate.setSessionFactory(sessionFactory);
        return hibernateTemplate;
    }
    /**
     * 支持HQL查询
     * */
    public Session HibernateSession(){
        Session session = hibernateTemplate().getSessionFactory().getCurrentSession();
        return session;
    }
    /**
     * 支持事务回滚
     * */
    public Transaction HibernateTransaction(){
        Transaction transaction = HibernateSession().beginTransaction();
        return transaction;
    }
}
